package com.db.main;

import android.text.TextUtils;
import com.db.utils.*;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {

    public static ThreadPoolExecutor executor;
    public static AtomicInteger got = new AtomicInteger();
    public static AtomicInteger req = new AtomicInteger();

    public static void main(String[] args) {

        executor = new ThreadPoolExecutor(2000,
                2000,
                300,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                new ThreadPoolExecutor.DiscardPolicy());

        // 允许核心线程在空闲时释放
        executor.allowCoreThreadTimeOut(true);

        // 生产环境
//        official();

        // 本地测试
        test();
    }

    /**
     * 生产环境需要启用该部分代码
     */
    public static void official() {
        while (true) {
            StringBuffer url = new StringBuffer(Constant.BASE_URL);
            // 增加Token
            url.append(Constant.GET_OFFER_PATH).append("?affiliateId=37&attributionPlatform=adjust&runningState=1&auditStatus=2").append("&token=").append(Constant.VERIFY_TOKEN);
            LogUtil.logApp("GetOffer", "getOffer url:" + url);
            String taskStr = null;
            try {
                taskStr = Downloader.doDownload(url.toString(), "GET", null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            LogUtil.logApp("GetOffer", "getOffer:" + taskStr);
            if (!TextUtils.isEmpty(taskStr)) {
                JSONObject jsonObject = new JSONObject(taskStr);
                Object jsonArray = jsonObject.get("data");
                if (jsonObject.getInt("code") == 200 && jsonArray != null && !((JSONArray) jsonArray).isEmpty()) {
                    JSONObject dataItem = ((JSONArray) jsonArray).getJSONObject(0);
                    String homePlatform = dataItem.getString("homePlatform");
                    got.incrementAndGet();
                    if ("Android".equalsIgnoreCase(homePlatform)) {
                        executor.execute(new Task(dataItem));
                    } else if ("IOS".equalsIgnoreCase(homePlatform)) {
                        executor.execute(new IOSTask(dataItem));
                    }
                }
            }

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 打印当前线程池状态
            LogUtil.logThreadPool("ThreadPool State", "active:" + executor.getActiveCount() + "-queue:" + executor.getQueue().size() + "-got:" + got + "-req:" + req);
        }
    }

    /**
     * 本地测试环境：测试单个任务
     */
    private static void test() {

        String taskId = "10105745".trim();

        // 2024/4/10 加token，防止其他人恶意获取offer资源
        StringBuffer url = new StringBuffer(Constant.BASE_URL);
        url.append(Constant.GET_OFFER_PATH)
                .append("?taskId=").append(taskId)
                .append("&token=").append(Constant.VERIFY_TOKEN)
                .append("testMode=ture");
        LogUtil.logApp("GetOffer", "getOffer url:" + url);

        String taskStr = Downloader.doDownload(url.toString(), "GET", null, null);
        LogUtil.logApp("GetOffer", "getOffer:" + taskStr);
        JSONObject jsonObject = new JSONObject(taskStr);
        Object jsonArray = jsonObject.get("data");
        if (jsonObject.getInt("code") == 200 && jsonArray != null && !((JSONArray) jsonArray).isEmpty()) {
            JSONObject dataItem = ((JSONArray) jsonArray).getJSONObject(0);
            String homePlatform = dataItem.getString("homePlatform");
            LogUtil.logApp("GetOffer", "homePlatform:" + homePlatform);
            if ("Android".equalsIgnoreCase(homePlatform)) {
                executor.execute(new Task(dataItem));
            } else if ("IOS".equalsIgnoreCase(homePlatform)) {
                executor.execute(new IOSTask(dataItem));
            }
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        LogUtil.logThreadPool("ThreadPool-State", "active:" + executor.getActiveCount() + "-queue:" + executor.getQueue().size() + "-got:" + got + "-req:" + req);
    }
}
